package org.jeecg.modules.achachievestandarditem.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import org.apache.commons.beanutils.BeanUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.achachievestandarditem.entity.AchAchieveStandardItem;
import org.jeecg.modules.achachievestandarditem.service.IAchAchieveStandardItemService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.achachievestandarditem.vo.AchAchieveStandardItemVo;
import org.jeecg.modules.achexaminationpaper.entity.AchExaminationPaper;
import org.jeecg.modules.achexaminationpaper.service.IAchExaminationPaperService;
import org.jeecg.modules.relation.relachstandarddistribution.entity.RelAchStandardDistribution;
import org.jeecg.modules.relation.relachstandarddistribution.service.IRelAchStandardDistributionService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: ach_achieve_standard_item
 * @author: baochangrong
 * @Date: 2022-03-16
 * @Version: V1.0
 */
@Api(tags = "ach_achieve_standard_item")
@RestController
@RequestMapping("/achachievestandarditem/achAchieveStandardItem")
@Slf4j
public class AchAchieveStandardItemController extends JeecgController<AchAchieveStandardItem, IAchAchieveStandardItemService> {
    @Autowired
    private IAchAchieveStandardItemService achAchieveStandardItemService;

    @Autowired
    private IAchExaminationPaperService examinationPaperService;

    @Autowired
    private IRelAchStandardDistributionService distributionService;

    /**
     * 分页列表查询
     *
     * @param achAchieveStandardItem
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "ach_achieve_standard_item-分页列表查询")
    @ApiOperation(value = "ach_achieve_standard_item-分页列表查询", notes = "ach_achieve_standard_item-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(AchAchieveStandardItem achAchieveStandardItem,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<AchAchieveStandardItem> queryWrapper = QueryGenerator.initQueryWrapper(achAchieveStandardItem, req.getParameterMap());
        Page<AchAchieveStandardItem> page = new Page<AchAchieveStandardItem>(pageNo, pageSize);
        IPage<AchAchieveStandardItem> pageList = achAchieveStandardItemService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 根据上级评分标准id获取标准明细记录
     */
    @AutoLog(value = "listBystandardId-列表查询")
    @ApiOperation(value = "listBystandardId-列表查询", notes = "listBystandardId-列表查询")
    @GetMapping(value = "/listBystandardId")
    public Result<?> listBystandardId(String achievementStandardId,
                                      HttpServletRequest req) {
        String tenantId = req.getHeader("tenant-id");
        List<AchAchieveStandardItemVo> achAchieveStandardItemVoList = achAchieveStandardItemService.listBystandardId(achievementStandardId, tenantId);
        return Result.OK(achAchieveStandardItemVoList);
    }


    /**
     * 添加
     *
     * @param achAchieveStandardItem
     * @return
     */
    @AutoLog(value = "ach_achieve_standard_item-添加")
    @ApiOperation(value = "ach_achieve_standard_item-添加", notes = "ach_achieve_standard_item-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AchAchieveStandardItem achAchieveStandardItem, HttpServletRequest req) {
        achAchieveStandardItem.setDelFlag(0);
        achAchieveStandardItemService.save(achAchieveStandardItem);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param achAchieveStandardItem
     * @return
     */
    @AutoLog(value = "ach_achieve_standard_item-编辑")
    @ApiOperation(value = "ach_achieve_standard_item-编辑", notes = "ach_achieve_standard_item-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody AchAchieveStandardItem achAchieveStandardItem) {
        achAchieveStandardItemService.updateById(achAchieveStandardItem);
        //返回成功1111
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ach_achieve_standard_item-通过id删除")
    @ApiOperation(value = "ach_achieve_standard_item-通过id删除", notes = "ach_achieve_standard_item-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        achAchieveStandardItemService.removeById(id);
        //清理废弃数据 （不能跨租户删除）
        int status = achAchieveStandardItemService.clearAbandon();
        return Result.OK("删除成功!");
    }

    private void deleteIsStandardItemEmpty(String standardId) {
        achAchieveStandardItemService.checkIsStandardItemEmpty(standardId);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "ach_achieve_standard_item-批量删除")
    @ApiOperation(value = "ach_achieve_standard_item-批量删除", notes = "ach_achieve_standard_item-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        AchAchieveStandardItem standardItem = achAchieveStandardItemService.getById(idList.get(0));
        if (this.achAchieveStandardItemService.removeByIds(Arrays.asList(ids.split(",")))) {
            deleteIsStandardItemEmpty(standardItem.getAchievementStandardId());
        }
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ach_achieve_standard_item-通过id查询")
    @ApiOperation(value = "ach_achieve_standard_item-通过id查询", notes = "ach_achieve_standard_item-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        AchAchieveStandardItem achAchieveStandardItem = achAchieveStandardItemService.getById(id);
        if (achAchieveStandardItem == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(achAchieveStandardItem);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param achAchieveStandardItem
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AchAchieveStandardItem achAchieveStandardItem) {
        return super.exportXls(request, achAchieveStandardItem, AchAchieveStandardItem.class, "ach_achieve_standard_item");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AchAchieveStandardItem.class);
    }

    @GetMapping("/queryAchievementsItemByRelObjIdType")
    public Result<?> queryAchievementsItemByRelObjIdType(AchAchieveStandardItemVo achAchieveStandardItemVo, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "30") Integer pageSize) {
        Page<AchAchieveStandardItemVo> page = new Page<AchAchieveStandardItemVo>(pageNo, pageSize);
        return Result.OK(achAchieveStandardItemService.queryAchievementsItemByRelObjIdType(page, achAchieveStandardItemVo));
    }

    /**
     * 一键生成计分规则
     * ach_examination_paper --> ach_achieve_standard_item(默认权重是1)
     */
    @GetMapping("/createStandardItemByExamPaper")
    public Result<?> createStandardItemByExamPaper(String examId) {
        if (Objects.isNull(examId)) return Result.error("考试信息不存在!!!");
        List<RelAchStandardDistribution> distributionList = distributionService.list(new QueryWrapper<RelAchStandardDistribution>(new RelAchStandardDistribution()
                .setPaperStandardEffective(1)
                .setRelObjId(examId)
                .setRelObjType("93")));
        if (distributionList.size() > 0) {
            return Result.error("已存在记录 请在清空后再次生成");
        }
        AchExaminationPaper paper = new AchExaminationPaper();
        paper.setDelFlag(0).setExaminationId(examId);
        QueryWrapper<AchExaminationPaper> queryWrapper = new QueryWrapper<>();
        queryWrapper.likeRight("del_flag", 0)
                .likeRight("examination_id", examId);
        List<AchExaminationPaper> papers = examinationPaperService.list(queryWrapper);
        if (Objects.isNull(papers) || papers.size() <= 0) {
            log.error("create Exam-Paper-Rules failed : {}", examId);
            return Result.error("此次考试卷为空 请添加考试卷后再次生成");
        }
        boolean createResult = achAchieveStandardItemService.createStandardItemByExamPaper(papers, examId);
        return createResult ? Result.OK() : Result.error("创建失败");
    }

    @GetMapping("/resetStandardItemByExamPaper")
    public Result<?> resetStandardItemByExamPaper(String examId) {
        if (Objects.isNull(examId)) return Result.error("考试信息不存在!!!");
        return achAchieveStandardItemService.resetStandardItemByExamPaper(examId) ? Result.OK() : Result.error("重置失败");
    }

    @GetMapping("/cleanAchItems")
    public Result<?> cleanAchItems(String examId) {
        if (Objects.isNull(examId)) return Result.error("考试信息不存在!!!");
        return achAchieveStandardItemService.cleanAchItems(examId) ? Result.OK() : Result.error("清除失败");
    }

    @PostMapping("/copyItem")
    public Result<?> copyStandardItem(@RequestBody AchAchieveStandardItem achAchieveStandardItem) {
        achAchieveStandardItem.setId(null);
        achAchieveStandardItemService.save(achAchieveStandardItem);
        return Result.OK("复制成功");
    }

    @PostMapping("/insetNewItem")
    public Result<?> insetNewStandardItem(@RequestBody String json) {
        if (Objects.isNull(json) || json.length() < 10) {
            log.error("params error : " + json);
            return Result.error("参数传递错误");
        }
        if (achAchieveStandardItemService.insertNewStandardItem(json) > 0) {
            return Result.OK("添加成功");
        }
        return Result.OK("添加失败");
    }


    /**
     * 获取针对试卷总分项的标准
     * getAchExamPaperStandardItem
     */
    @AutoLog(value = "ach_achieve_standard_item-分页列表查询")
    @ApiOperation(value = "ach_achieve_standard_item-分页列表查询", notes = "ach_achieve_standard_item-分页列表查询")
    @GetMapping(value = "/getAchExamPaperStandardItem")
    public Result<?> getAchExamPaperStandardItem(AchAchieveStandardItemVo achAchieveStandardItemVo,
                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                 HttpServletRequest req) {
        String exaPapProItemCode = achAchieveStandardItemVo.getExaPapProItemCode();
        String tenantId = req.getHeader("tenant-id");
        Page<AchAchieveStandardItemVo> page = new Page<AchAchieveStandardItemVo>(pageNo, pageSize);
        IPage<AchAchieveStandardItemVo> itemVoList = achAchieveStandardItemService.getAchExamPaperStandardItem(page, exaPapProItemCode, tenantId);
        return Result.OK(itemVoList);
    }

    /**
     * 快速添加
     * speedAddStandardItem
     * @return
     */
    @AutoLog(value = "ach_achieve_standard_item-快速添加")
    @ApiOperation(value = "ach_achieve_standard_item-快速添加", notes = "ach_achieve_standard_item-快速添加")
    @PostMapping(value = "/speedAddStandardItem")
    public Result<?> speedAddStandardItem(@RequestBody JSONObject jsonObject, HttpServletRequest req) {
        String tenantId = req.getHeader("tenant-id");
        boolean saveStatu = achAchieveStandardItemService.speedAddStandardItem(jsonObject,tenantId);
        if (saveStatu){
            return Result.OK("快速添加成功！");
        }else {
            return Result.error("快速添加出错！");
        }
    }


}
